//
//  PersonBViewController.swift
//  OnceNectar
//
//  Created by 吴凌 on 2018/8/1.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import LTScrollView
import Networking
import Alamofire
import PKHUD
import SwiftyJSON

class PersonBViewController: UIViewController, LTTableViewProtocal {
    
    private lazy var tableView: UITableView = {
        let H: CGFloat = view.bounds.height  - 64
        let tableView = tableViewConfig(CGRect(x: 0, y: 0, width: view.bounds.width, height: H), self, self, nil)
        return tableView
    }()
    
    var isMine:Bool = false
    var userId:String?
    var page:Int = 1
    var totalPage:Int = 0
    var videoData:[VideoModel] = []
    
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        view.addSubview(tableView)
        glt_scrollView = tableView
        
        tableView.register(UINib(nibName: "\(ConsultaionTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "\(ConsultaionTableViewCell.self)")
        
        let headerAction:Selector = #selector(headerRefresh)
        header.setRefreshingTarget(self, refreshingAction: headerAction)
        tableView.mj_header = header
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
        tableView.mj_footer = footer
        
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        
        headerRefresh()
    }
    
    /// 获取视频列表
    func fetchVideoList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(myContentUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        if self.page == 1{
                                            self.videoData.removeAll()
                                            self.tableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.tableView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            
                                            let dic = subject.dictionary!
                                            var model = VideoModel(fromDic: dic)
                                            let labels = dic["labels"]?.array!
                                            
                                            model.initLabels(arr: labels!)
                                            
                                            let label = dic["label"]
                                            if !(label?.isEmpty)!{
                                                model.initLabel(dic: (label?.dictionary!)!)
                                            }
                                            let author = dic["author"]
                                            if !(author?.isEmpty)!{
                                                model.initAuthor(dic: (author?.dictionary!)!)
                                            }
                                            let grade = dic["author"]!["grade"]
                                            if !grade.isEmpty{
                                                model.author?.initGrade(dic: (grade.dictionary!))
                                            }
                                            let channel = dic["channel"]
                                            if !(channel?.isEmpty)!{
                                                model.initChannel(dic: (channel?.dictionary!)!)
                                            }
                                            
                                            self.videoData.append(model)
                                        }
                                        if self.totalPage == self.videoData.count{
                                            self.tableView.mj_footer=nil
                                        }
                                        else{
                                            self.tableView.mj_footer = self.footer
                                        }
                                        self.tableView.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page == 1{
                                            self.tableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.tableView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page == 1{
                                    self.tableView.mj_header.endRefreshing()
                                }
                                else{
                                    self.tableView.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    func showToast(msg :String) -> Void {
        self.view.makeToast("一度蜜：" + msg, duration: 1.5, position: .center)
    }
}

extension PersonBViewController {
    
    // 顶部刷新
    @objc func headerRefresh(){
        page = 0
        self.footerRefresh()
        
    }
    // 底部刷新
    @objc func footerRefresh(){
        page += 1
        var parameters: [String: Any] = ["page":page,"pageSize":10,"type":2]
        if !self.isMine {
            parameters["otherUserId"] = self.userId
        }
        self.fetchVideoList(parameters: parameters)
    }
}


extension PersonBViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return videoData.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "\(ConsultaionTableViewCell.self)") as? ConsultaionTableViewCell
        cell?.showVideoData(model: videoData[indexPath.row])
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = VideoDetailViewController(nibName: ("\(VideoDetailViewController.self)"), bundle: nil, type: HomeVCSelect.video)
        vc.model = videoData[indexPath.row]
        self.navigationController?.pushViewController(vc, animated: true)
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 260
    }
}
